package chatNI;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import common.Message;


/**
 * UDPCom:
 * Classe contains the communication UDP socket.
 * @author bazile gaye
 */

//extends Thread

public class UDPCom {

    private final static int size = 1000;

    private ChatNI ni;
    private int numPort;
    private DatagramSocket sock;

    /**
     *
     */
    public UDPCom(){}

    /**
     * Constructor
     * @param port an integer above 1024.
     * @param chat the network interface chatNI.
     * @throws SocketException bad creation of the socket.
     */
    public UDPCom(int port, ChatNI chat) throws SocketException{
            this.numPort = port;
            this.ni = chat;
            this.sock = new DatagramSocket(this.numPort);
    }


    /**
     * send:
     * Function use to send a Message in the socket UDP (in broadcast or unicast).
     * @param ipAdress address of destination (broadcast or unicast).
     * @param portDest port number of destination.
     * @param mess message to send.
     */
    protected void sendMessage(InetAddress ipAdress, int portDest, Message mess) {

            byte[] buf = new byte[size];
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

            try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(mess);
            oos.flush();
            oos.close();


            } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("Error transform MEssage to DatagramPacket");
            }
    buf = baos.toByteArray();

    // On crée le packet Datagram
    DatagramPacket pac = new DatagramPacket(buf, buf.length, ipAdress, portDest);

    //On envoie le packet sur le socket
    try {
            sock.send(pac);
    } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Problème dans l'envoie de packet sur le socket UDP.");
    }
    }


    /**
     * interrupt:
     * Function use to stop the thread and close the socket.
     */
    public void interrupt() {
       sock.close();
    }


}
